package com.example.hosptial.util;

import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;

import java.io.IOException;
import java.sql.SQLException;

/**
 * HTTP响应处理工具类
 */
public class ResponseUtil {
    private static final Logger logger = LoggerUtil.getLogger();

    /**
     * 发送成功响应
     * @param resp HTTP响应对象
     * @param message 成功信息
     */
    public static void sendSuccess(HttpServletResponse resp, String message) {
        try {
            resp.getWriter().write("{\"message\": \"" + message + "\"}");
        } catch (IOException e) {
            logger.error("响应写入失败：", e);
        }
    }

    /**
     * 发送错误响应
     * @param resp HTTP响应对象
     * @param status HTTP状态码
     * @param message 错误信息
     */
    public static void sendError(HttpServletResponse resp, int status, String message) {
        try {
            resp.setStatus(status);
            resp.getWriter().write("{\"error\": \"" + message + "\"}");
        } catch (IOException e) {
            logger.error("响应写入失败：", e);
        }
    }

    /**
     * 处理业务逻辑并发送响应
     * @param resp HTTP响应对象
     * @param action 业务逻辑
     */
    public static void handleOperation(HttpServletResponse resp, Operation action) {
        try {
            action.execute();
        } catch (SQLException e) {
            logger.error("数据库错误：", e);
            String errorMessage = e.getMessage().contains("foreign key") 
                ? "数据库错误：找不到相关记录" 
                : "数据库错误：" + e.getMessage();
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage);
        } catch (IllegalArgumentException e) {
            logger.error("参数错误：", e);
            sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "参数错误：" + e.getMessage());
        } catch (SecurityException e) {
            logger.error("权限错误：", e);
            sendError(resp, HttpServletResponse.SC_FORBIDDEN, "权限错误：" + e.getMessage());
        } catch (IOException e) {
            logger.error("IO错误：", e);
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IO错误：" + e.getMessage());
        } catch (Exception e) {
            logger.error("未知错误：", e);
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器错误");
        }
    }

    /**
     * 处理业务逻辑并返回结果
     * @param resp HTTP响应对象
     * @param action 业务逻辑
     * @return 业务逻辑执行结果
     */
    public static <T> T handleOperationWithResult(HttpServletResponse resp, OperationWithResult<T> action) {
        try {
            return action.execute();
        } catch (SQLException e) {
            logger.error("数据库错误：", e);
            String errorMessage = e.getMessage().contains("foreign key") 
                ? "数据库错误：找不到相关记录" 
                : "数据库错误：" + e.getMessage();
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage);
        } catch (IllegalArgumentException e) {
            logger.error("参数错误：", e);
            sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "参数错误：" + e.getMessage());
        } catch (SecurityException e) {
            logger.error("权限错误：", e);
            sendError(resp, HttpServletResponse.SC_FORBIDDEN, "权限错误：" + e.getMessage());
        } catch (IOException e) {
            logger.error("IO错误：", e);
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IO错误：" + e.getMessage());
        } catch (Exception e) {
            logger.error("未知错误：", e);
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器错误");
        }
        return null;
    }

    /**
     * 业务操作接口
     */
    @FunctionalInterface
    public interface Operation {
        void execute() throws Exception;
    }

    /**
     * 带返回值的业务操作接口
     */
    @FunctionalInterface
    public interface OperationWithResult<T> {
        T execute() throws Exception;
    }
} 